﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CardsServer.Tools;

namespace CardsServer
{
    public partial class DbSet : Form
    {
        private bool connOK = false;    
        public DbSet(bool err)
        {
            InitializeComponent();
            if (!err)
            {
                lbl_info.Text = "连接数据库失败!请修改配置信息。";
                lbl_info.ForeColor = Color.Red;
            }
            sqlconn sc = MyConfig.getConnection();
            txt_Database.Text = sc.database;
            txt_server.Text = sc.server;
            txt_uid.Text = sc.uid;
            txt_password.Text = sc.pwd;

        }

        /// <summary>
        /// 修改服务器连接字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_update_Click(object sender, EventArgs e)
        {
            checkDbConn();
            if (connOK)
            {
                if (MyConfig.setConnection(txt_server.Text, txt_Database.Text, txt_uid.Text, txt_password.Text) == 1)
                { 
                    MessageBox.Show("修改数据库连接成功！");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("修改数据库连接失败！");
                }
            }
            else
            {
                MessageBox.Show("连接到指定数据库失败！");
            }
        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            checkDbConn();
        }

        /// <summary>
        /// 检测数据库连接
        /// </summary>
        /// <returns></returns>
        private string checkDbConn()
        {
            //帐套数据库连接字符串
           string connstr = string.Format("server={0};database={1};user id={2};pwd={3}", txt_server.Text, txt_Database.Text, txt_uid.Text, txt_password.Text);
            SqlConnection conn = new SqlConnection(connstr);

            try
            {
                conn.Open();
                connOK = true;
                lbl_info.Text = "连接数据库成功!";
                lbl_info.ForeColor = Color.ForestGreen;
                return string.Empty;
            }
            catch (Exception ex)
            {
                lbl_info.Text = "连接数据库失败!请修改配置信息。";
                lbl_info.ForeColor = Color.Red;
                return "连接数据库失败!"+ex.Message;
            }
        }


    }
}
